<template>
  <resize-drawer
    :title="title"
    @onCloseDraw="closeDraw"
    @onCancelFun="cancelFun"
    @onSave="onSave"
    :isShowMoreBtn="true"
    :drawer="drawerShow"
    :size="576"
    class="addForm"
  >
    <template #column>
      <el-form :model="form" label-width="100px" ref="formRef" :rules="rules" label-position="top">
        <el-form-item prop="number">
          <template #label>
            <span>SIP号<span>自定义SIP号码，支持13位数字格式</span></span>
          </template>
          <el-input v-model.trim="form.number" placeholder="请输入13位纯数字" :disabled="numberDisabled"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <template #label>
            <span>密码<span>支持6-18位数字、大小写字母格式</span></span>
          </template>
          <el-input
            v-model.trim="form.password"
            maxlength="18"
            placeholder="请输入6-18位的数字、大小写字母"
            show-word-limit
          ></el-input>
        </el-form-item>
        <el-form-item prop="nat">
          <template #label>
            <span>是否NAT</span>
          </template>
          <el-radio-group v-model="form.nat">
            <el-radio :label="true">是</el-radio>
            <el-radio :label="false">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="codingFormat">
          <template #label>
            <span>
              语音编码
              <span>编码格式默认位G711U，可根据话机设备情况和网络情况进行调整</span>
            </span>
          </template>
          <el-select v-model="form.codingFormat" filterable multiple placeholder="请选择">
            <el-option v-for="item in voiceNumList" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定员工">
          <el-select v-model="form.agentId" placeholder="请选择" filterable clearable>
            <el-option
              v-for="item in bindingEmployeesList"
              :key="item._id"
              :label="`${item.agentName}[${item.agentNumber}]`"
              :value="item._id"
            />
          </el-select>
        </el-form-item>
      </el-form>
    </template>
  </resize-drawer>
</template>

<script lang="ts">
import { defineComponent, reactive, toRefs, getCurrentInstance, onMounted, computed } from 'vue'
import resizeDrawer from '@/common/components/resize-drawer/index.vue'
import { addSIPNo, updateSIPNo } from '@app/call-center/apis/number-manage'
import { ElMessage } from 'element-plus'
import { numberAndLetter, number13 } from '@/common/utils/validate'
import { commonStore } from '@/common/store/modules/common'
import mcCache from '@/common/utils/mc-get-cache'
import { userModule } from '@/common/store/modules/user'

const commonModule = commonStore()

interface State {
  title: string
  drawerShow: boolean
  form: any
  rules: any
  voiceNumList: any
  numberDisabled: boolean
}
export default defineComponent({
  name: 'addSIPNum',
  components: {
    resizeDrawer
  },
  props: {
    numType: {
      type: String,
      default: ''
    }
  },
  emits: ['onRefresh'],
  // ----------------生命周期-----------------------
  setup(props, { emit }) {
    const USERMODULE = userModule()
    const validateNumber = (rule: any, value: any, callback: any) => {
      if (value !== '') {
        if (!number13(value) || value.length > 13) {
          callback(new Error('仅支持13位的数字格式'))
        } else {
          callback()
        }
      } else {
        callback(new Error('必填'))
      }
    }
    const validatePass = (rule: any, value: any, callback: any) => {
      if (value !== '') {
        if (!numberAndLetter(value) || value.length < 6 || value.length > 18) {
          callback(new Error('密码仅支持6-18位的数字、大小写字母'))
        } else {
          callback()
        }
      } else {
        callback(new Error('必填'))
      }
    }
    const state: State = reactive({
      title: '新建SIP号',
      drawerShow: false,
      form: {
        number: '',
        codingFormat: ['G711U'],
        password: '',
        nat: true,
        agentId: ''
      },
      rules: {
        number: [{ required: true, validator: validateNumber, trigger: 'blur' }],
        password: [{ required: true, validator: validatePass, trigger: 'blur' }],
        nat: [{ required: true, message: '请选择', trigger: 'change' }],
        codingFormat: [{ required: true, message: '请选择', trigger: 'change' }]
      },
      voiceNumList: [
        { label: 'G711A', value: 'G711A' },
        { label: 'G711U', value: 'G711U' },
        { label: 'GSM', value: 'GSM' },
        { label: 'G729', value: 'G729' },
        { label: 'ILBC', value: 'ILBC' },
        { label: 'VP8', value: 'VP8' }
      ], //语音编码列表
      numberDisabled: false
    })

    const instance: any = getCurrentInstance()

    const openAddSIPNo = async (row: any) => {
      if (row) {
        state.title = '编辑SIP号'
        state.form.number = row.number
        state.form.password = row.password
        state.form.nat = row.nat
        state.form.agentId = row.agentId
        state.form.codingFormat = row.codingFormat
        state.numberDisabled = true
        state.rules.number = []
      } else {
        state.title = '新建SIP号'
        state.numberDisabled = false
        state.rules.number = [{ required: true, validator: validateNumber, trigger: 'blur' }]
        state.form = {
          number: '',
          password: '',
          nat: true,
          agentId: '',
          codingFormat: ['G711U'],
          numberDisabled: false
        }
      }
      // 打开抽屉
      state.drawerShow = true
    }
    const bindingEmployeesList: any = computed(() => {
      return commonModule.publicCache.userCache
    })

    // 关闭抽屉
    const closeDraw = () => {
      state.drawerShow = false
    }

    // 关闭抽屉
    const cancelFun = () => {
      state.drawerShow = false
    }

    // 抽屉保存
    const onSave = () => {
      const sendData: any = {}
      sendData.accountId = USERMODULE.accountId || ''
      sendData.list = []
      sendData.list.push(state.form)
      instance?.refs.formRef.validate((valid: boolean) => {
        if (valid) {
          if (props.numType == 'add') {
            sendData.designate = true
            addSIPNo(sendData).then((res) => {
              if (res && res.success) {
                ElMessage.success('保存成功')
                emit('onRefresh')
                mcCache.$addOneCache('sipNum', res.data, 'id', '') // 编辑
              }
            })
          } else {
            updateSIPNo(sendData).then((res) => {
              if (res && res.success) {
                ElMessage.success('编辑成功')
                emit('onRefresh')
                mcCache.$updateCache('sipNum', { ...sendData, status: 1 }, 'id', '') // 编辑
              }
            })
          }
          state.drawerShow = false
        }
      })
    }

    return {
      ...toRefs(state),
      openAddSIPNo,
      closeDraw,
      cancelFun,
      onSave,
      bindingEmployeesList
    }
  }
})
</script>

<style lang="stylus" scoped>
:deep(.el-select)
    width 100%
</style>
